package com.haoyu.number.Thread;

/**
 * @author: 蒿雨
 * @create: 2021-12-10 17:02
 * @description:
 */
public class Demo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        MyThread1 myThread1 = new MyThread1(ticket);
        myThread1.setName("窗口1");
        MyThread2 myThread2 = new MyThread2(ticket);
        myThread2.setName("窗口2");
        MyThread3 myThread3 = new MyThread3(ticket);
        myThread3.setName("窗口3");
        //
        myThread1.start();
        myThread2.start();
        myThread3.start();

    }
}

class Ticket {
    int tickets = 0;
    int flag = 1;

    public synchronized void sellA() {
        if (flag != 1) {
            try {
                //售出一张票，进行上锁
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        flag = 2;
        if (tickets < 100) {
            tickets++;
            System.out.println(Thread.currentThread().getName() + "售票，编号为：" + tickets);

        }
        //唤醒所有休眠的线程
        notifyAll();
    }

    public synchronized void sellB() {
        if (flag != 2) {
            try {
                //售出一张票，进行上锁
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        flag = 3;
        if (tickets < 100) {
            tickets++;
            System.out.println(Thread.currentThread().getName() + "售票，编号为：" + tickets);

        }
        //唤醒所有休眠的线程
        notifyAll();


    }

    public synchronized void sellC() {
        if (flag != 3) {
            try {
                //售出一张票，进行上锁
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        flag = 1;
        if (tickets < 100) {
            tickets++;
            System.out.println(Thread.currentThread().getName() + "售票，编号为：" + tickets);

        }
        //唤醒所有休眠的线程
        notifyAll();
    }

}


class MyThread1 extends Thread {

    Ticket ticket;

    public MyThread1(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while (ticket.tickets < 100) {
            ticket.sellA();
        }
    }
}

class MyThread2 extends Thread {
    Ticket ticket;

    public MyThread2(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while (ticket.tickets < 100) {
            ticket.sellB();
        }
    }
}

class MyThread3 extends Thread {
    Ticket ticket;

    public MyThread3(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while (ticket.tickets < 100) {
            ticket.sellC();
        }
    }
}
